<?php
class wapi_users extends wapi_mod_base {
	function _construct(){
		if ($this->firstrun){
			$this->db_create();
		}
	}
	private function db_create(){
		global $wapi;
		// Called on new install of wapi
	    // Users
		$sql = "CREATE TABLE users (
		user_id TEXT PRIMARY KEY NOT NULL,
		first_name TEXT NOT NULL,
		last_name TEXT NOT NULL,
		email TEXT NOT NULL,
		password_hash TEXT,
		password_salt TEXT,
		local_only INTEGER NOT NULL,
		state INTEGER NOT NULL
		)";
		/*** run the create table query ***/
		$wapi->db->exec($sql);
		# Make the user_id field CASE INSENSITIVE and UNIQUE
		$sql = 'CREATE UNIQUE INDEX uciidxUserID ON users (user_id COLLATE NOCASE)';
		$wapi->db->exec($sql);
		$this->setup_initial_accounts();
	}
	private function db_user_create(){
		global $wapi;
		// Called on new user first run

	}
	public function login($user_id,$password){
		global $wapi;
		$ret = false;
		$user_id = strtolower($user_id);
	    $sql = "SELECT * FROM users WHERE LOWER(user_id) = '$user_id';";
	    $salt = '';
	    $err = '';
		if ($wapi->db->query($sql)){
			$res = $wapi->db->results;
			foreach ($res as $row){
		        $salt = $row['password_salt'];
		        $hash = $row['password_hash'];
		        $state = $row['state'];
		        break;
		    }
		}
	    if ($salt != '') {
	    	if ($state == 1) {
	    		if ($this->generateHash($salt,$password) == $hash) {
	    			$ret = true;
					# Load user credentials
					$this->load_user($row['user_id']);
					$wapi->events->raise('user_login');
					return true;

	    		} else {
	    			$err = "User name or password incorrect.";
	    		}
	    	} else {
	    		$err = 'Account inactive. See admin.';
	    	}
	    } else {
	    	$err = "User not found";
	    }
	    return $err;
	}
	public function load_user($user_id){
		global $wapi;
		$sql = "SELECT first_name,last_name,email,local_only,state FROM users WHERE LOWER(user_id) = '".strtolower($user_id)."';";
		// Add security to this function to prevent unauthorized use
		if ($wapi->db->query($sql)){
			$res = $wapi->db->results;
			if ($wapi->user->user_id != '' && $user_id != $wapi->user->user_id) {
				$_SESSION = array();
				$wapi->events->raise('user_unload');
			}
			$wapi->user->user_id = $user_id;
			$wapi->user->info = $res[0];
			$_SESSION['wapp_user_id'] = $user_id;
			//setcookie("WAPP_USER", $wapi->user->user_id);
			$wapi->events->raise('user_loaded');
			return true;
		}
		return false;
	}
	private function setup_initial_accounts(){
		# Admin Account
		$this->add('Admin','admin','System','Admin','',1);
		# System Account
		$this->add('System','system','Guest','User','',1,1);
		# Guest account. The default account used by anyone not logged in.
		$this->add('Guest','guest','Guest','User','',1);
	}
	function add($user_id,$password,$first_name,$last_name,$email,$state=0,$local_only=0){
		global $wapi;
		# returns error string or empty string if no error
		$salt = $this->generateSalt();
		$pass_hash = $this->generateHash($salt,$password);
		$sql="insert into users (user_id, password_hash, password_salt, state, email, first_name, last_name,local_only)";
		$sql .=" values ('$user_id','$pass_hash','$salt',$state,'$email','$first_name','$last_name',$local_only);";
		return $wapi->db->exec($sql);
	}
	function verify($user_id,$password){
		global $wapi;
		$user_id = strtolower($user_id);
	    $sql = "SELECT * FROM users WHERE LOWER(user_id) = '$user_id';";
		if ($wapi->db->query($sql)){
			$res = $wapi->db->results;
			$row = $res[0];
	        $salt = $row['password_salt'];
	        $hash = $row['password_hash'];
    		if ($this->generateHash($salt,$password) == $hash) {
    			return true;
    		}
		}
		return false;
	}
	function del($user_id){
		global $wapi;
		$user_id = strtolower($user_id);
	    $sql = "DELETE FROM users WHERE LOWER(user_id) = '$user_id';";
		if ($wapi->db->exec($sql) == 1){
    		return true;
		}
		return false;
	}
	function exists($user_id){
		global $wapi;
		if ($user_id == '') return false;
		$user_id = strtolower($user_id);
	    $sql = "SELECT user_id FROM users WHERE LOWER(user_id) = '$user_id';";
		if ($wapi->db->query($sql)){
    		return true;
		}
		return false;
	}
	function user($user_id=null){
		global $wapi;
		if ($user_id == null){
			$user_id = $wapi->user['user_id'];
		}
		$user_id = strtolower($user_id);
	    $sql = "SELECT user_id, first_name, last_name, email, state FROM users WHERE LOWER(user_id) = '$user_id';";
		if ($wapi->db->query($sql)){
			$res = $wapi->db->results;
			return $res[0];
		}
		return null;
	}
//	function login($user_id,$password){
//		if ($this->verify($user_id,$password)){
//			$wapi->user = $this->user($user_id);
//			$_SESSION('WAPI_USER_ID') = $wapi->user['user_id'];
//		}
//	}
	private function generateHash($salt, $plainText){
	    return sha1($salt . $plainText);
	}
	private function generateSalt(){
		$salt_len=8;
	    return $this->key_gen($salt_len);
	}
	private function key_gen($key_len){
	    return substr(md5(uniqid(rand(), true)), 0, $key_len);
	}
	private function com_register_user($data){
		# vaildate input first
		if (!is_string($data->user)){
			echo 'Error';
			return false;
		}
		if (!is_string($data->pass)){
			echo 'Error';
			return false;
		}
		if (!is_string($data->first_name)){
			echo 'Error';
			return false;
		}
		if (!is_string($data->last_name)){
			echo 'Error';
			return false;
		}
		if (!is_string($data->email)){
			echo 'Error';
			return false;
		}
		if (!preg_match("/^[a-zA-Z0-9_]{5,20}$/", $data->pass)) {
		    echo 'Invalid password.';
		    return false;
		}
		if (!preg_match("/^[a-zA-Z0-9_]{3,20}$/", $data->user)) {
		    echo 'Invalid username.';
		    return false;
		}
		if (!preg_match("/^[a-zA-Z0-9_]{2,20}$/", $data->first_name)) {
		    echo 'Invalid first name.';
		    return false;
		}
		if (!preg_match("/^[a-zA-Z0-9_]{2,20}$/", $data->last_name)) {
		    echo 'Invalid last name.';
		    return false;
		}
		if (!preg_match("/^[a-zA-Z0-9_]{8,32}$/", $data->email)) {
		    echo 'Invalid email.';
		    return false;
		}
		return $this->users->add($data->user,$data->pass,$data->first_name,$data->last_name,$data->email);
	}
}
?>